package com.ncucoder.soms.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 邮件工具类
 *
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @date 2019-07-10
 */
public class MailUtils {

    /**
     * 发送者
     */
    public static String from;
    /**
     * 授权码
     */
    private static String secret;
    /**
     * 邮件类型
     * 例如: text/html;charset=utf-8
     */
    private static String type;


    static {
        // 读取配置文件
        from = PropertyUtils.properties.getProperty("mail.from");
        secret = PropertyUtils.properties.getProperty("mail.secret");
        type = PropertyUtils.properties.getProperty("mail.type");

    }


    public static void send(String to, String subject, String content) {

        Session session = Session.getInstance(PropertyUtils.properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, secret);
            }
        });
        Message message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setContent(content, type);
            Transport.send(message);

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
